Bokeh Tutorial

1.7 Animate (optional)

Exercise: Add a title plot for the app with month and year that gets updated with the plot animation


In [1]:
# Imports
import numpy as np
import netCDF4

from bokeh.plotting import vplot, hplot, cursession, output_server, show

from viz import climate_map, timeseries, legend, get_slice

In [2]:
# Data
data = netCDF4.Dataset('data/Land_and_Ocean_LatLong1.nc')
t = data.variables['temperature']

In [3]:
# Output option
output_server("climate")


Using saved session configuration for http://localhost:5006/
To override, pass 'load_from_config=False' to Session

In [4]:
from bokeh.plotting import figure

# Data 
year = 1850
month = 1

years = [str(x) for x in np.arange(1850, 2015, 1)]

months = [str(x) for x in np.arange(1, 13, 1)]
months_str = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

month_str = months_str[month-1]

# New text Plot
title = figure(width=1200, height=100, x_range=(0, 1200), y_range=(0, 100), toolbar_location=None,
        x_axis_type=None, y_axis_type=None, outline_line_color="#FFFFFF", tools="", min_border=0)

title.text(x=500, y=5, text=[month_str], text_font_size='36pt', text_color='black', name="month", text_font="Georgia")
title.text(x=350, y=5, text=[str(year)], text_font_size='36pt', text_color='black', name="year",text_font="Georgia")


Out[4]:
<bokeh.plotting.Figure at 0x1111b9c50>

In [5]:
# Plots
climate_map = climate_map()
timeseries = timeseries()
legend = legend()

In [6]:
# Create layout
map_legend = hplot(climate_map, legend)
layout = vplot(title, map_legend, timeseries)

In [7]:
# Show
show(layout)

In [8]:
# Select data source for climate_map and month and year
renderer = climate_map.select(dict(name="image"))
ds = renderer[0].data_source

month_renderer = title.select(dict(name="month"))
month_ds = month_renderer[0].data_source

year_renderer = title.select(dict(name="year"))
year_ds = year_renderer[0].data_source

In [ ]:
# Modify the previous loop: updates the image, month and year data sources
import time

while True:
    for year_index in np.arange(2000, 2015, 1):
        year_ds.data["text"] = [str(year_index)]
        for month_index in np.arange(1, 13, 1):
            month_ds.data["text"] = [months_str[month_index-1]]
            image = get_slice(t, year_index, month_index)
            ds.data["image"] = [image]
            cursession().store_objects(ds, year_ds, month_ds)
            time.sleep(0.2)

Exercise: Modify your viz.py file to include the new title plot